<template>
  <div
    class="login_body"
    v-loading.fullscreen.lock="loadingKey"
    :element-loading-text="loadingText"
  >
    <div class="login_box">
      <div class="login_box_right">
        <div class="login_box_right_title">用户登录</div>
        <div class="login_box_right_form">
          <el-form ref="ruleFormRef" :model="form" :rules="rules">
            <el-form-item prop="phone" label="手机号：">
              <el-input v-model="form.phone" style="width: 360px"></el-input>
            </el-form-item>
            <el-form-item prop="phone_code" label="验证码：">
              <div class="code_box">
                <el-input
                  v-model="form.phone_code"
                  style="width: 250px; margin-right: 10px"
                ></el-input>
              </div>
              <el-button @click="getCodeFn()" :disabled="!getCodeKey">{{
                getCodeTime
              }}</el-button>
            </el-form-item>
          </el-form>
        </div>
        <el-button type="danger" style="width: 440px" @click="onSubmit()"
          >立即登录</el-button
        >
      </div>
    </div>
  </div>
  >
</template>

<script setup>
import userApi from "../api/index";
import { reactive, ref, getCurrentInstance } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import router from "../router/index";
import { useStore } from "vuex";

const store = useStore();
const form = reactive({
  phone: "",
  phone_code: "",
});
const getCodeTime = ref("获取验证码"); //获取验证码显示
const codeInterval = ref(null); //验证码重新获取时间
const getCodeKey = ref(true); //控制获取验证码按钮是否禁止点击
const loadingKey = ref(false); //页面加载状态控制
const loadingText = ref(); //页面加载状态显示文字
const ruleFormRef = ref(); //登录表单内容

//手机号验证
const validatephone = function (rule, value, callback) {
  if (value === "") {
    return callback(new Error("请输入手机号"));
  } else {
    let telText =
      /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-9])\d{8}$/;
    if (!telText.test(value)) {
      callback(new Error("手机号格式不正确"));
    } else {
      callback();
    }
  }
};

//验证码验证
const validatecode = function (rule, value, callback) {
  if (value === "") {
    callback(new Error("请输入验证码"));
  } else {
    callback();
  }
};

//表单校验
const rules = reactive({
  phone: [{ required: true, validator: validatephone, trigger: "blur" }],
  phone_code: [{ required: true, validator: validatecode, trigger: "blur" }],
});

//发送获取验证码
const getCodeFn = () => {
  // if (!ruleFormRef) return;
  ruleFormRef.value.validateField("phone", async (valid) => {
    // console.log(valid);
    if (valid != "") {
      if (getCodeKey.value) {
        ElMessageBox.confirm("确认发送短信验证码?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
        }).then(async () => {
          let data = {
            phone: form.phone,
          };
          getCodeKey.value = false;
          setCodeTimeFn();
          const res = await userApi.getCode(data);
          if (res.data.code != 0) {
            getCodeKey.value = true;
            clearInterval(codeInterval.value);
            getCodeTime.value == "获取验证码";
            ElMessage.error(res.data.msg);
          } else {
            getCodeKey.value = false;
            setCodeTimeFn();
            clearInterval(codeInterval.value);
          }
        });
      }
    }
  });
};

//验证码重新获取倒计时
const setCodeTimeFn = () => {
  let time = 30;
  codeInterval.value = setInterval(function () {
    if (time > 0) {
      getCodeTime.value = "重新发送(" + time + ")";
      time = time - 1;
    } else {
      getCodeTime.value = "获取验证码";
      getCodeKey.value = true;
      clearInterval(codeInterval.value);
    }
  }, 1000);
};

//登录
const onSubmit = () => {
  if (!ruleFormRef) return;
  ruleFormRef.value.validate(async (valid) => {
    if (valid) {
      loadingKey.value = true;
      const res = await userApi.login(form);
      if (res.data) {
        if (res.data.code == 0) {
          loadingKey.value = false;
          loadingText.value = "登录中...";
          store.commit("set_loginToken", res.data.token);
          store.commit("set_loginUserId", res.data.userid);
          console.log('登录',res.data.token);
          router.push("/home");
        } else {
          ElMessage.error(res.data.msg);
        }
      } else {
        ElMessage.error("服务器内部错误");
      }
    } else {
      return false;
    }
  });
};
</script>

<style scoped>
.login_body {
  width: 100vw;
  height: 100vh;
  background-color: #ffffff;
  display: flex;
  align-items: center;
  justify-content: center;
}

.login_box {
  width: 1075px;
  height: 623px;
  box-shadow: 0px 5px 46px 0px rgba(191, 191, 191, 0.47);
  overflow: hidden;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.login_box_right {
  width: 678px;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.login_box_right_title {
  font-size: 22px;
  font-weight: bold;
  color: #e71432;
}

.login_box_right_form {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 40px;
  margin-bottom: 10px;
}

.code_box {
  width: 257px;
  display: flex;
  align-items: center;
}
</style>
